import { useCallback, memo, useMemo, useRef } from 'react';
import { Modal, Checkbox, Button, Radio } from 'antd';
import { SchemaForm } from 'gantd';
import { View } from '@/components/searchform/interface';
import { cloneDeep, get, set } from 'lodash';
import { WrappedFormUtils } from 'antd/lib/form/Form.d';

// 配置共享视图的权限 write 可编辑也可以查看 read 只能查看 none 不能编辑与查看
export type CompanyViewAuth = 'write' | 'read' | 'none';

export interface SaveAsModalProps {
  visible?: boolean;
  loading?: boolean;
  onCancel?: () => void;
  onSubmit?: (values: object) => void;
  customViews: View[];
  companyViews: View[];
  companyViewAuth: CompanyViewAuth;
  viewType: View['viewType'];
}

const customComponents = [
  {
    name: 'SmartSearchRadioGroud',
    component: Radio.Group,
  },
  {
    name: 'SmartSearchCheckbox',
    component: Checkbox,
  },
];

const schema = {
  type: 'object',
  propertyType: {
    type: {
      componentType: 'SmartSearchRadioGroud',
      title: tr('视图类型'),
      props: {
        options: [
          { value: 'custom', label: tr('个人视图') },
          { value: 'company', label: tr('共享视图') },
        ],
      },
      options: {
        initialValue: 'custom',
      },
    },
    name: {
      componentType: 'Input',
      title: tr('视图名称'),
      props: {
        placeholder: tr('请输入视图名称'),
      },
    },
    isDefault: {
      componentType: 'SmartSearchCheckbox',
      title: tr('设为默认'),
    },
  },
};

function getRules(viewType: 'custom' | 'company', customViews: View[], companyViews: View[]) {
  let allNames = (viewType != 'company' ? customViews : companyViews).map((item) => item.name);

  return [
    {
      message: tr('视图名称重复!'),
      validator: function (rule: any, value: string = '', callback: Function) {
        let res = value.trim();
        if (!res) {
          rule.message = tr('视图名称必填');
          callback(true);
        } else if (allNames.includes(res)) {
          callback(true);
        }
        callback(undefined);
      },
    },
  ];
}

function SaveAsModal(props: SaveAsModalProps) {
  const { visible, loading, onCancel, onSubmit, customViews, companyViews, viewType, companyViewAuth, ...nextProps } =
    props;

  const formRef = useRef(null);

  const showSchema = useMemo(() => {
    const res = cloneDeep(schema);

    // 根据共享视图权限设置 共享视图 是否可选
    if (companyViewAuth != 'write') {
      set(res, 'propertyType.type.props.options[1].disabled', true);
    }

    // 动态设置视图名称的验证规则
    set(res, 'propertyType.name', {
      ...get(res, 'propertyType.name'),
      options: {
        rules: getRules(viewType, customViews, companyViews),
      },
      dependencies: ['type'],
      onDependenciesChange: ([type]: any[], field: any, form: WrappedFormUtils) => {
        // 改变schema
        return {
          ...field,
          options: {
            ...field.options,
            // 视图类型变化时需要更新下验证规则
            rules: getRules(type, customViews, companyViews),
          },
        };
      },
    });

    return res;
  }, [viewType, customViews, companyViews]);

  const onOk = useCallback(async () => {
    const res = await formRef.current?.validateForm?.();
    const { errors, values } = res;
    if (errors) return;
    onSubmit && onSubmit(values);
  }, [onSubmit]);

  const stoppropagation = useCallback((e) => {
    if (e) {
      e.stopPropagation();
      e.nativeEvent.stopImmediatePropagation();
    }
  }, []);

  return (
    <div onMouseDown={stoppropagation} onDoubleClick={stoppropagation} style={{ display: 'inline-block' }}>
      <Modal
        visible={visible}
        title={tr('另存视图')}
        onCancel={onCancel}
        centered
        destroyOnClose
        footer={
          <div>
            <Button size="small" icon="close-circle" onClick={onCancel}>
              {tr('取消')}
            </Button>
            <Button size="small" type="primary" icon="save" loading={loading} onClick={onOk}>
              {tr('保存')}
            </Button>
          </div>
        }
        zIndex={1010}
        {...nextProps}
      >
        <SchemaForm schema={showSchema} data={{}} customFields={customComponents} wrappedComponentRef={formRef} />
      </Modal>
    </div>
  );
}
export default memo<SaveAsModalProps>(SaveAsModal);
